# coding=utf8
import xlwt
import json

from export_excel.export import ExportExcel


class TxtExportExcel(ExportExcel):
    def __init__(self, *files, excel_name):
        self.files = files
        self.excel_name = excel_name

        self.count = 0
        self.isone = False
        self.keys = []

    def start(self, keys=None):
        print("准备开始")
        self.work = xlwt.Workbook(encoding='utf-8')
        self.book = self.work.add_sheet('Sheet 0', cell_overwrite_ok=True)

        if keys:
            self.write_col_one(keys)

        for filei in self.files:
            print("正在执行，{}".format(filei))
            self.execute(filei)

        self.work.save(self.excel_name)
        print("全部结束")

    def write_col_one(self, raw_value):
        self.write_col(0, raw_value)

        self.isone = True
        self.keys = raw_value

    def write_col(self, row_num, raw_value):
        max_raw_num = 60000

        if row_num % max_raw_num == 0 and row_num != 0:
            self.book = self.work.add_sheet(
                'Sheet {0}'.format(str(row_num / max_raw_num)),
                cell_overwrite_ok=True
            )

        for col_num, col_value in enumerate(raw_value):
            if not isinstance(col_value, str) and not isinstance(col_value, bytes):
                col_value = json.dumps(col_value, ensure_ascii=False)

            self.book.write(row_num % max_raw_num, col_num, col_value)

        self.count += 1

    def execute(self, filei):
        count = 0
        s = open(filei, encoding="utf8")
        while 1:
            line = s.readline()
            if not line:
                break

            count += 1

            line = line.strip()
            if line == "":
                continue

            try:
                data = json.loads(line)

                if not self.isone:
                    self.write_col_one(data.keys())
                else:
                    self.execute_data(data)
            except:
                print(count)

    def execute_data(self, data):
        resutls = []

        for key in self.keys:
            ks = key.split(".")
            if len(ks) == 1:
                value = data[key]
            else:
                value = data
                for k in ks:
                    value = value[k]

            resutls.append(value)

        self.write_col(self.count, resutls)
